package com.moyun.common.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.moyun.common.utils.SpringContextUtil;
import com.moyun.common.utils.ValidateUtil;
import com.moyun.common.mapstruct.SysUserConvertMapper;
import com.moyun.model.param.system.ImportUserParam;
import com.moyun.model.po.system.SysUserEntity;
import com.moyun.service.system.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : ybx
 * @description: 系统用户监听类
 * @date : 2022-09-19 10:35:09
 **/
@Slf4j
public class SysUserEntityExcelListener<T> extends BaseExcelAnalysisEventListener<T> {

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("==>成功的数量为:{},失败的数量为:{}<==", successCount, errorCount);
        data.forEach(System.out::println);
        /**
         * 解析结束销毁不用的资源
         */
        this.saveData(data);
        data.clear();
    }

    @Override
    protected void saveData(List<T> data) {
        /**
         * 此类并没有交由Spring管理, 获取已创建对象 可以通过 SpringContextUtil 工具来获取
         */
        SysUserService sysUserService = SpringContextUtil.getBean(SysUserService.class);
        SysUserConvertMapper sysUserConvertMapper = SpringContextUtil.getBean(SysUserConvertMapper.class);
        List<SysUserEntity> collect = data.stream().map(t -> sysUserConvertMapper.importUserParamtoSysUserEntity((ImportUserParam) t)).collect(Collectors.toList());
        sysUserService.saveBatch(collect);

    }

    /**
     * 如果不对数据做任何校验,则直接返回true
     **/
    @Override
    protected boolean dataValid(T t) {
        List<String> errors = ValidateUtil.validate(t);
        this.setValidMsg(StringUtils.strip(errors.toString(), "[]"));
        return CollectionUtils.isEmpty(errors);
    }


}